package com.wl.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.mysql.cj.util.StringUtils;
import com.wl.mapper.UsersMapper;
import com.wl.pojo.Users;
import com.wl.service.SendSmsService;
import com.wl.util.MyUtil;
import com.wl.util.MybatisUtils;
import com.wl.util.RedisUtil;
import com.wl.util.SendSmsUtils;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: treeHole
 * @author: 吴磊
 * @create: 2021-07-06 22:33
 */
public class SendSmsServiceImpl implements SendSmsService {

    /**
     * 获取手机验证码
     *
     * @param telPhone
     * @return
     */
    @Override
    public Map<String, Object> getSmsCode(String telPhone) throws ClientException {
        UsersMapper usersMapper = MybatisUtils.getMapper(UsersMapper.class);
        Users user = usersMapper.getUserByUserTelPhoneOrUserEmail(telPhone);
        HashMap<String, Object> map = new HashMap<>();
        if (user != null) {
            //说明这个手机号已经被注册
            map.put("theTelPhoneIsOk", false);
            map.put("isSendOk", false);
        } else {
            //说明可以注册
            Jedis jedis = RedisUtil.getJedis();
            if (!jedis.exists(telPhone)) {
                map.put("theTelPhoneIsOk", true);
                //如果redis里面存在这个手机号，说明这个手机号的验证码没过期
                String code = MyUtil.getUUID().substring(0, 5);
                HashMap<String, Object> codeMap = new HashMap();
                codeMap.put("code", code);
                boolean isSend = SendSmsUtils.sendSms(telPhone, codeMap);
                if (isSend) {
                    map.put("isSendOk", true);
                    //将该用户的验证码加入到redis并设置有效时间为5分钟
                    jedis.setex(telPhone, 60L * 5, code);
                } else {
                    map.put("isSendOk", false);
                }
            } else {
                map.put("theTelPhoneIsOk", false);
                map.put("isSendOk", false);
            }
            jedis.close();
        }
        return map;
    }

    /**
     * 验证验证码
     *
     * @param telPhone
     * @param smsCode
     * @return
     */
    @Override
    public Map<String, Object> validationSmsCode(String telPhone, String smsCode) {
        Jedis jedis = RedisUtil.getJedis();
        String phone_ver = jedis.get(telPhone);
        HashMap<String, Object> map = new HashMap<>();
        if (phone_ver == null) {
            map.put("varIsOk", false);
        }
        if (StringUtils.isNullOrEmpty(phone_ver)) {
            map.put("varIsOk", false);
        } else {
            map.put("varIsOk", phone_ver.equalsIgnoreCase(smsCode));
        }
        jedis.close();
        return map;
    }
}
